package com.bizmda.bizsip.sink.config;

import com.bizmda.bizsip.common.BizException;
import com.bizmda.bizsip.config.SinkConfigMapping;
import com.bizmda.bizsip.sink.Sink;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

/**
 * @author 史正烨
 */
@Slf4j
@Configuration
public class SinkConfiguration {
    @Value("${bizsip.config-path:#{null}}")
    private String configPath;

    @Autowired
    private CachingConnectionFactory connectionFactory;

    @Bean
    public SinkConfigMapping sinkConfigMapping() {
        try {
            return new SinkConfigMapping(this.configPath);
        } catch (BizException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Bean
    @Scope("prototype")
    public Sink Sink() {
        return new Sink();
    }

    @Bean
    @ConditionalOnProperty(name = "spring.rabbitmq.host",matchIfMissing = false)
    public RabbitTemplate rabbitTemplate(){
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
//        rabbitTemplate.setMandatory(true);
        rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
//
//        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
//            @Override
//            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
//                // TODO
//            }
//        });
//        rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
//            @Override
//            public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
//                log.debug("消息丢失:exchange({}),route({}),replyCode({}),replyText({}),message:{}",exchange,routingKey,replyCode,replyText,message);
//            }
//        });
        return rabbitTemplate;
    }
}
